<template>
  <div class="dashboard-container">
    <el-card shadow="never">
      <!-- 将地图容器的div改为双标签形式 -->
      <div ref="mapContainer" class="map" />
      <div class="controls">
        <button @click="startDrawing">开始绘制多边形</button>
        <button :disabled="!isDrawing" @click="completeDrawing">完成</button>
        <button :disabled="!isDrawing" @click="cancelDrawing">取消</button>
        <button v-if="currentPolygon" @click="savePolygon">保存多边形</button>
        <button v-if="currentPolygon" @click="deletePolygon">删除多边形</button>
        <button @click="saveMapAsImage">保存地图为图片</button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import html2canvas from "html2canvas";
import { useUserStore } from "@/store/modules/user";
import router from "@/router";

// 地图容器的引用
const mapContainer = ref<HTMLElement | null>(null);
let map: AMap.Map;
let mouseTool: AMap.MouseTool;
// 当前绘制的多边形
let currentPolygon: AMap.Polygon | null = null;
// 是否正在绘制状态
const isDrawing = ref(false);
// 高德地图API的key，需要替换为你自己申请的有效key
const apiKey = "c82372a2fbfc00f4b34488c43b2c5e0c";

// 新增：用于表示地图是否初始化成功的状态变量
const mapInitialized = ref(false);

// 初始化地图及相关绘制工具
const initMap = () => {
  AMapLoader.load({
    key: apiKey,
    version: "3.0",
    plugins: ["AMap.MouseTool"],
  })
    .then((AMap) => {
      console.log("高德地图 API 加载成功");
      if (!mapContainer.value) {
        console.error("地图容器未找到，请检查模板中的 ref 属性");
        return;
      }

      map = new AMap.Map(mapContainer.value, {
        center: [105.38192, 29.15041],
        layers: [new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()],
        zoom: 13,
      });

      mouseTool = new AMap.MouseTool(map);

      mouseTool.on("draw", (event: AMap.MouseTool.DrawEvent) => {
        currentPolygon = event.obj;
        isDrawing.value = false;
        console.log("多边形绘制完成:", currentPolygon.getPath());
      });

      map.on("rightclick", () => {
        if (isDrawing.value) {
          mouseTool.close();
          isDrawing.value = false;
        }
      });

      mapInitialized.value = true;
      console.log("地图初始化成功");
    })
    .catch((error) => {
      console.error("加载高德地图API时发生错误:", error);
      // 添加更多详细的错误信息
      if (error instanceof Error) {
        console.error("错误类型:", error.name);
        console.error("错误消息:", error.message);
        console.error("堆栈跟踪:", error.stack);
      } else {
        console.error("未知错误:", error);
      }
    });
};

// 开始绘制多边形
const startDrawing = () => {
  if (!mapInitialized.value) {
    console.error("地图尚未初始化，请稍后再试");
    return;
  }
  if (currentPolygon) {
    map.remove(currentPolygon);
    currentPolygon = null;
  }
  mouseTool.polygon({
    strokeColor: "#FFA43D",
    strokeOpacity: 1,
    strokeWeight: 6,
    fillColor: "rgba(254, 168, 71, 0.37)",
    fillOpacity: 0.4,
    strokeStyle: "solid",
  });
  isDrawing.value = true;
};
// 完成绘制（停止工具，但保留多边形）
const completeDrawing = () => {
  mouseTool.close();
  isDrawing.value = false;
  saveMapAfterCompleteDrawing();
};

// 提取保存地图图片的公共函数
const saveMapToLocalStorage = async (container: HTMLElement) => {
  try {
    const canvas = await html2canvas(container);
    // const imageData = canvas.toDataURL("image/png");
    localStorage.setItem("savedMapImage", imageData);
    alert("地图图片已成功保存到本地存储！");
  } catch (error) {
    console.error("保存地图图片时发生错误:", error);
  }
};

// 完成绘制后保存地图为图片的具体实现
const saveMapAfterCompleteDrawing = () => {
  if (mapContainer.value && currentPolygon) {
    saveMapToLocalStorage(mapContainer.value);
  }
};

// 取消绘制（清除当前多边形）
const cancelDrawing = () => {
  mouseTool.close(true);
  if (currentPolygon) {
    map.remove(currentPolygon);
    currentPolygon = null;
  }
  isDrawing.value = false;
};

// 保存多边形到 localStorage
const savePolygon = () => {
  if (currentPolygon) {
    const polygonPath = currentPolygon.getPath().map((point: AMap.LngLat) => ({
      lng: point.lng,
      lat: point.lat,
    }));
    try {
      localStorage.setItem("savedPolygon", JSON.stringify(polygonPath));
      alert("多边形已保存！");
    } catch (error) {
      console.error("保存多边形到 localStorage 时发生错误:", error);
      // 根据具体需求，可在这里对组件状态进行调整，比如显示一个错误提示给用户
    }
  }
};

// 删除多边形
const deletePolygon = () => {
  if (currentPolygon) {
    map.remove(currentPolygon);
    currentPolygon = null;
    localStorage.removeItem("savedPolygon");
    alert("多边形已删除！");
  }
};

// 保存地图为图片到本地存储（localStorage）
const saveMapAsImage = () => {
  if (mapContainer.value) {
    saveMapToLocalStorage(mapContainer.value);
  }
};

// 加载保存的多边形（如果有）
const loadSavedPolygon = () => {
  const savedPolygon = localStorage.getItem("savedPolygon");
  if (savedPolygon) {
    try {
      const polygonPath = JSON.parse(savedPolygon);
      if (Array.isArray(polygonPath) && polygonPath.every((point) => point.lng && point.lat)) {
        const path = polygonPath.map(
          (point: { lng: number; lat: number }) => new AMap.LngLat(point.lng, point.lat)
        );
        currentPolygon = new AMap.Polygon({
          path,
          strokeColor: "#FFA43D",
          strokeOpacity: 1,
          strokeWeight: 6,
          fillColor: "rgba(254, 168, 71, 0.37)",
          fillOpacity: 0.4,
        });
        map.add(currentPolygon);
      }
    } catch (error) {
      console.error("加载保存的多边形时发生错误:", error);
      // 根据具体需求，可在这里清除之前可能存在的当前多边形状态，避免后续出现异常
      currentPolygon = null;
    }
  }
};

onMounted(() => {
  initMap();
  loadSavedPolygon();

  // 加载保存的地图图片（如果有）
  const savedMapImage = localStorage.getItem("savedMapImage");
  if (savedMapImage) {
    const img = new Image();
    img.src = savedMapImage;
    img.onload = () => {
      if (mapContainer.value) {
        mapContainer.value.appendChild(img);
      }
    };
  }
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.map {
  width: 100%;
  height: 500px;
}

.controls {
  position: absolute;
  top: 10px;
  left: 10px;
  display: flex;
  gap: 10px;
}

button {
  padding: 5px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  cursor: pointer;
  border-radius: 5px;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

button:hover:enabled {
  background-color: #38a871;
}
</style>
